package com.yuandian.ops.workbench.service.impl;

import com.yuandian.api.management.entity.ConfSystem;
import com.yuandian.api.management.feign.RemoteSystemService;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.ops.workbench.mapper.SystemYwgztMapper;
import com.yuandian.ops.workbench.po.SystemHealthParamsYwgzt;
import com.yuandian.ops.workbench.service.ISystemYwgztService;
import com.yuandian.ops.workbench.vo.SystemHealthInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>系统service接口实现类</p>
 *
 * @author: LinShiHe
 * @date: 2021-05-18
 */
@Slf4j
@Service
public class SystemYwgztServiceImpl implements ISystemYwgztService {

	@Autowired
	private SystemYwgztMapper systemYwgztMapper;

	@Autowired
	private RemoteSystemService remoteSystemService;

	/**
	 * 根据系统分类与系统名称查询系统健康度列表
	 *
	 * @param params
	 * @return
	 */
	@Override
	public R<Object> getSystemHealthList(SystemHealthParamsYwgzt params) {
		// 根据域名获取该域下所有的系统
		List<SystemHealthInfoVo> systemList = new ArrayList<>();
		List<Integer> systemIds = new ArrayList<>();
		R<List<ConfSystem>> result = null;
		try {
			long sTime = System.currentTimeMillis();
			result = remoteSystemService.getSystemsAndDomain();
			log.info("[运维工作台]-[远程调用-后台配置服务]-[获取系统域信息接口]-耗时: {} MS", System.currentTimeMillis() - sTime);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("[运维工作台]-[远程调用-后台配置服务]-[获取系统域信息接口]报错: {}" + e.getMessage());
		}

		if (!Objects.isNull(result)) {
			List<ConfSystem> data = result.getData();
			if (CollectionUtils.isNotEmpty(data)) {
				for (ConfSystem datum : data) {
					SystemHealthInfoVo systemHealthInfoVo = new SystemHealthInfoVo();
					systemHealthInfoVo.setSystemId(datum.getId());
					systemHealthInfoVo.setSystemName(datum.getName());
					systemHealthInfoVo.setSystemDomainId(datum.getDomainCode());
					systemList.add(systemHealthInfoVo);
					// 封装查询条件 '系统ID列表'
					systemIds.add(systemHealthInfoVo.getSystemId());
				}
			} else {
				log.info("[运维工作台]-查询系统健康度列表-不存在相关系统!");
				return R.ok(new ArrayList<>());
			}
		}

		params.setSystemIds(systemIds);
		List<SystemHealthInfoVo> dataList = systemYwgztMapper.selectSystemHealthList(params);
		// 把各个系统归属到各个域里面
		if (CollectionUtils.isNotEmpty(dataList)) {
			for (SystemHealthInfoVo dataL : dataList) {
				for (SystemHealthInfoVo systemL : systemList) {
					if (dataL.getSystemId() != null &&
							dataL.getSystemId().equals(systemL.getSystemId())) {

						systemL.setHealthRate(dataL.getHealthRate());
						break;
					}
				}
			}
		}
		return R.ok(systemList);
	}

}
